<?php

class Adept_Session_Http implements ArrayAccess
{

    protected $started;

    static $instance;

    public function __construct()
    {
        $this->started = false;
    }

    static public function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function start()
    {
        if ($this->started) {
            return false;
        }
        @session_start();
        $this->started = true;
        return true;
    }

    public function close()
    {
        @session_write_close();
    }

    public function getValue($name)
    {
        if (isset($_SESSION[$name])) {
            $value = $_SESSION[$name];
            if ($value instanceof Adept_Util_Serializer) {
                return $value->getSubject();
            } else {
                return $value;
            }
        } else {
            return null;
        }
    }

    public function setValue($name, $value)
    {
        if (is_object($value)) {
            $serializer = new Adept_Util_Serializer($value);
            $_SESSION[$name] = $serializer;
        } else {
            $_SESSION[$name] = $value;
        }
    }

    public function hasValue($name)
    {
        return isset($_SESSION[$name]);
    }

    public function removeValue($name)
    {
        if (isset($_SESSION[$name])) {
            session_unregister($name);
            unset($_SESSION[$name]);
        }
    }

    public function offsetGet($offset)
    {
        return $this->getValue($offset);
    }

    public function offsetSet($offset, $value)
    {
        $this->setValue($offset, $value);
    }

    public function offsetUnset($offset)
    {
        $this->removeValue($offset, null);
    }

    public function offsetExists($offset)
    {
        return $this->hasValue($offset);
    }

}
